import { defineStore } from 'pinia'
import { loginApi, getUserInfoApi  } from '../../api/login'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {}
  }),
  actions: {
    setToken(token) {
      this.token = token
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },
    removeUserInfo() {
      this.userInfo = {}
    },
    removeToken() {
      this.token = ''
    },
    loginAction({ phone, password }) {
      return new Promise((resolve, reject) => {
        loginApi({ phone, password }).then(res => {
              this.setToken(res.accessToken)
              resolve()
          }).catch(error => {
              reject(error)
        })
      })
    },
    getUserInfoAction() {
      return new Promise((resolve, reject) => {
        getUserInfoApi().then(data => {
          this.setUserInfo(data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    logoutAction() {
      this.removeToken()
      this.removeUserInfo()
    }
  },
  persist: true
})